#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include "flv.h"


int validateFLV(int fd, struct stat *st, int offset)
{
	unsigned char buff[FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAG];

	// Check for minimal FLV file length
	if(st->st_size < offset + (FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAG))
		return 0;

	if (lseek(fd, offset, SEEK_SET) < 0)
		return 0;
	if (read(fd, buff, FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAG) != FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAG)
		return 0;

	if(buff[0] != 'F' || buff[1] != 'L' || buff[2] != 'V')
		return 0;

	if(FLV_UI8(&buff[3]) != 1)
		return 0;

	if(FLV_UI32(&buff[5]) != FLV_SIZE_HEADER)
		return 0;
	return 1;
}

int readFLVTag(struct FLVTag_t *flvtag, off_t offset, int fd) 
{
	unsigned char buff[FLV_SIZE_TAGHEADER];

	if (lseek(fd, offset, SEEK_SET) < 0)
		return 0;
	if (read(fd, buff, FLV_SIZE_TAGHEADER) != FLV_SIZE_TAGHEADER)
		return 0;
	flvtag->offset = offset;
	flvtag->tagtype = FLV_UI8(buff);
	flvtag->datasize = (size_t)FLV_UI24(&buff[1]);
	flvtag->timestamp = FLV_TIMESTAMP(&buff[4]);
	flvtag->tagsize = FLV_SIZE_TAGHEADER + flvtag->datasize;
	return 1;
}
